import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:window_manager/window_manager.dart';
import 'package:win32/win32.dart';
import 'dart:ffi';
import 'dart:ui' as ui;
import 'package:ffi/ffi.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await windowManager.ensureInitialized();

  WindowOptions windowOptions = const WindowOptions(
    size: ui.Size(400, 520),
    center: true,
    skipTaskbar: false,
    alwaysOnTop: false,
  );

  windowManager.waitUntilReadyToShow(windowOptions, () async {
    await windowManager.show();
    await windowManager.focus();
  });

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Message List',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MessageListPage(),
    );
  }
}

class MessageListPage extends StatefulWidget {
  @override
  _MessageListPageState createState() => _MessageListPageState();
}

class _MessageListPageState extends State<MessageListPage> with WindowListener {
  late FocusNode _focusNode;
  List<Message> messages = [];
  int _selectedIndex = 0;
  int? _pressedIndex;
  ScaffoldFeatureController<SnackBar, SnackBarClosedReason>? _snackBarController;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    windowManager.addListener(this);
    _loadMessages();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    windowManager.removeListener(this);
    super.dispose();
  }

  Future<void> _loadMessages() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String>? savedMessages = prefs.getStringList('messages');

    if (savedMessages != null) {
      setState(() {
        messages = savedMessages
            .map((e) => Message.fromJson(jsonDecode(e)))
            .toList();
      });
    }
  }

  Future<void> _saveMessages() async {
    final prefs = await SharedPreferences.getInstance();
    final encodedMessages = messages.map((e) => jsonEncode(e.toJson())).toList();
    await prefs.setStringList('messages', encodedMessages);
  }

  void _addMessage(Message message) {
    setState(() {
      messages.add(message);
    });
    _saveMessages();
  }

  void _copyMessageContent(int index) {
    Clipboard.setData(ClipboardData(text: messages[index].content));
    _showSnackBar('已复制: ${messages[index].content}');
    setState(() {
      _pressedIndex = index;
    });

    // 延时恢复按压效果
    Future.delayed(const Duration(milliseconds: 200), () {
      if (_pressedIndex == index) {
        setState(() {
          _pressedIndex = null;
        });
      }
    });
  }

  void _showSnackBar(String message) {
    _snackBarController?.close(); // 关闭前一个提示
    _snackBarController = ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 1),
      ),
    );
  }

  void _handleKey(RawKeyEvent event) {
    if (event is RawKeyDownEvent) {
      setState(() {
        if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
          _selectedIndex = (_selectedIndex - 1) < 0
              ? messages.length - 1
              : _selectedIndex - 1;
        } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
          _selectedIndex = (_selectedIndex + 1) % messages.length;
        } else if (event.logicalKey == LogicalKeyboardKey.enter) {
          _copyMessageContent(_selectedIndex);
        }
      });
    }
  }

  void _onMessageTap(int index) {
    setState(() {
      _selectedIndex = index; // 同步焦点
    });
    _copyMessageContent(index);
  }

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: _focusNode..requestFocus(),
      onKey: _handleKey,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('消息列表'),
          actions: [
            IconButton(
              icon: const Icon(Icons.add),
              onPressed: () async {
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => AddMessagePage()),
                );
                if (result != null && result is Message) {
                  _addMessage(result);
                }
              },
            ),
          ],
        ),
        body: ListView.builder(
          itemCount: messages.length,
          itemBuilder: (context, index) {
            final message = messages[index];
            final isSelected = _selectedIndex == index;
            final isPressed = _pressedIndex == index;

            return GestureDetector(
              onTap: () => _onMessageTap(index),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 100),
                padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                decoration: BoxDecoration(
                  color: isPressed
                      ? Colors.blue.shade100
                      : (isSelected ? Colors.blue.shade50 : Colors.white),
                  border: Border(
                    bottom: BorderSide(color: Colors.grey.shade300),
                  ),
                ),
                child: Row(
                  children: [
                    CircleAvatar(
                      child: const Icon(Icons.message_rounded, color: Colors.white),
                      backgroundColor: Colors.blueAccent,
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            message.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              color: isSelected ? Colors.blue : Colors.black,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            message.content,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(color: Colors.black54),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      message.time,
                      style: const TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}

class AddMessagePage extends StatelessWidget {
  final TextEditingController titleController = TextEditingController();
  final TextEditingController contentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('添加消息')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: titleController,
              decoration: const InputDecoration(labelText: '消息标题'),
            ),
            TextField(
              controller: contentController,
              decoration: const InputDecoration(labelText: '消息内容'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                final message = Message(
                  title: titleController.text,
                  content: contentController.text,
                  time: DateTime.now().toLocal().toString().substring(11, 16),
                  icon: Icons.message_rounded,
                );
                Navigator.pop(context, message);
              },
              child: const Text('保存'),
            ),
          ],
        ),
      ),
    );
  }
}

class Message {
  final String title;
  final String content;
  final String time;
  final IconData icon;

  Message({
    required this.title,
    required this.content,
    required this.time,
    required this.icon,
  });

  Map<String, dynamic> toJson() => {
        'title': title,
        'content': content,
        'time': time,
        'icon': icon.codePoint,
      };

  factory Message.fromJson(Map<String, dynamic> json) {
    return Message(
      title: json['title'],
      content: json['content'],
      time: json['time'],
      icon: IconData(json['icon'], fontFamily: 'MaterialIcons'),
    );
  }
}
